<template>
  <a-layout>
    <a-layout-content style="padding: 24px 50px; min-height: 280px;">
      <a-space size="4">
        <a-input-search
            v-model:value="param.value"
            placeholder="输入电子书名称"
            enter-button="搜索"
            size="large"
            @search="onSearch"
        />
        <a-button type="primary" @click="add" size="large">新增</a-button>
      </a-space>
      <a-table
               :data-source="ebooks"
               :row-key="record => record.id"
               :pagination="pagination"
               :loading="loading"
               @change="handleTableChange"
      >
        <a-table-column title="封面" data-index="cover" >
          <template #default="{ text: cover }">
            <img v-if="cover" :src="cover" alt="avatar" />
          </template>
        </a-table-column>
        <a-table-column title="名称" data-index="name" ></a-table-column>
        <a-table-column title="分类">
            <template v-slot="{ record }">
              <span> {{ getCategoryName(record.category1Id) }} / {{ getCategoryName(record.category2Id) }}</span>
            </template>
        </a-table-column>

<!--        <a-table-column title="分类一" data-index="category1Id" ></a-table-column>-->
<!--        <a-table-column title="分类二" data-index="category2Id" ></a-table-column>-->
        <a-table-column title="文档数" data-index="docCount" ></a-table-column>
        <a-table-column title="阅读数" data-index="viewCount" ></a-table-column>
        <a-table-column title="点赞数" data-index="voteCount" ></a-table-column>
        <a-table-column title="操作" key="action" >
            <template v-slot="{text, record}">
              <a-space size="small">
                <router-link :to="'/admin/doc?ebookId='+ record.id">
                  <a-button type="primary">文档管理</a-button>
                </router-link>
                <a-button type="primary" @click="edit(record)">编辑</a-button>
                <a-popconfirm
                    title="确认要删除吗？删除后不可恢复"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="handleDelete(record)"
                >
                  <a-button type="primary" danger>删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
        </a-table-column>
      </a-table>
    </a-layout-content>
  </a-layout>

  <a-modal
      title="电子书表单-编辑"
      v-model:visible="editVisible"
      :confirm-loading="editConfirmLoading"
      @ok="editHandleOk"
      okText="提交"
      cancelText="取消"
  >
    <a-form :model="ebook" :label-col="{span: 6}" :wrapper-col="{span:14}">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover" />
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name" />
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader v-model:value="categoryIds" :options="level1"
                    :fieldNames="{label: 'name', value:'id', children: 'children'}" placeholder="请选择" />
      </a-form-item>
<!--      <a-form-item label="分类一">-->
<!--        <a-input v-model:value="ebook.category1Id" />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="分类二">-->
<!--        <a-input v-model:value="ebook.category2Id" />-->
<!--      </a-form-item>-->
      <a-form-item label="描述">
        <a-textarea  v-model:value="ebook.description" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import {SmileOutlined, DownOutlined} from '@ant-design/icons-vue';
import {defineComponent, ref} from 'vue';
import axios from 'axios'
import { message } from 'ant-design-vue';
import {Tool} from "@/util/tool.ts";

export default defineComponent({
  setup() {
    const ebooks = ref();
    const param = ref({});
    const pagination = ref({
      current: 1,
      pageSize: 2,
      total: 0,
    });
    const loading = ref(false);
    // 查询所有数据
    const handleQuery = (params) => {
      loading.value = true;
      axios.get("/ebook/list", {params}).then((response) => {
        const data = response.data;
        loading.value = false;
        if (data.code == 200){
          ebooks.value = data.data.list;

          pagination.value.current = params.page;
          pagination.value.total = parseInt(data.data.total);
        } else {
           message.error(data.message)
        }
      });
    };
    const handleTableChange = (pagination) =>{
        handleQuery({
          page: pagination.current,
          size: pagination.pageSize
        });
    }

    // 编辑
    const editVisible = ref(false);
    const editConfirmLoading = ref(false);
    const ebook = ref();

    const editHandleOk = () =>{
      editConfirmLoading.value = true;
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];
      axios.post("/ebook/save", ebook.value).then( (resp) => {
        editVisible.value = false;
        editConfirmLoading.value = false;
        if (resp.data.code == 200) {
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        } else{
          message.error("编辑失败")
        }
      })
    }

    const edit = (record) => {
      editVisible.value = true;
      ebook.value = Tool.copy(record);
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id];
    }

    const add = () => {
      editVisible.value = true;
      ebook.value = {};
    }

    const handleDelete = (record) => {
       let id = record.id;
        axios.delete("/ebook/delete/" + id).then( (resp) => {
          if (resp.data.code == 200) {
            handleQuery({
              page: pagination.value.current,
              size: pagination.value.pageSize
            });
          } else {
            message.error("删除失败")
          }
        })
    }

    const onSearch = (name) => {
      handleQuery({
        page: pagination.value.current,
        size: pagination.value.pageSize,
        name
      })
    }

    // 分类
    const categoryIds = ref();
    const level1 = ref();
    const categorys = ref([]);
    const handleQueryCategory = () => {
      loading.value = true;
      axios.get("/category/list").then((response) => {
        const data = response.data;
        loading.value = false;
        if (data.code == 200){
          categorys.value = data.data;
          level1.value = Tool.array2Tree(data.data, 0);
        } else {
          message.error(data.message)
        }
      });
    }

    const getCategoryName = (id) => {
      let result = "";
      categorys.value.forEach( (e) => {
        if (e.id == id){
          result = e.name;
        }
      });
      return result;
    }

    return {
      ebooks,
      pagination,
      loading,
      handleQuery,
      handleTableChange,
      editVisible,
      editConfirmLoading,
      editHandleOk,
      edit,
      ebook,
      add,
      handleDelete,
      param,
      onSearch,
      categoryIds,
      level1,
      handleQueryCategory,
      getCategoryName
    };
  },
  mounted() {
    let that = this;
    this.handleQuery({
      page: 1,
      size: that.pagination.pageSize
    });
    this.handleQueryCategory();
  },

  components: {
    SmileOutlined,
    DownOutlined,
  },
});

</script>


<style scoped>
  img {
    width: 50px;
    height: 50px;
  }
</style>